package com.nulldev.util.web.nTubeExtensions.Redwood.pages;

import java.time.Duration;
import java.util.regex.Pattern;

import com.nulldev.util.JVM.JVM;
import com.nulldev.util.data.variable;
import com.nulldev.util.io.file.FileUtil;
import com.nulldev.util.web.HttpClient.HttpClient;
import com.nulldev.util.web.HttpServer3.Response;
import com.nulldev.util.web.HttpServer3.pages.v3.HttpPage3;
import com.nulldev.util.web.YouTubeExtractor.YouTubeExtractor;
import com.nulldev.util.web.nTube.resources.project_redwood.RedwoodResource;
import com.nulldev.util.web.nTubeExtensions.Redwood.Redwood;

public class RedwoodCaptionsFile extends HttpPage3 {

	protected RedwoodCaptionsFile(final String id) {
		super(id);
		this.setCachingMethod(CachingMethod.SHORT_CACHE);
	}

	public static RedwoodCaptionsFile make() throws Exception {
		if (!Redwood.ENABLE_CAPTIONS)
			return null;
		YouTubeExtractor.extractor.waitFor();
		Redwood.player.waitFor();
		final String s = Redwood.player_url.get().replace("base.js", "captions.js");
		final String n = HttpClient.getString().url(s).timeout(Duration.ofSeconds(60)).create().dataThenClose();
		captions.set(n);
		final String ur = "/" + s.split(ID_SPLIT_PATTERN)[1];
		Redwood.log.info("[Redwood] captions url: " + ur);
		return new RedwoodCaptionsFile(ur);
	}

	private static final variable<String> captions = new variable<String>();

	@SuppressWarnings("resource")
	@Override
	public Response onRequest(final Request request) {
		if (!Redwood.ENABLE_AUTO_UPDATING)
			return new Response(200, FileUtil.getResourceStream(RedwoodResource.class, "youtube_captions.js")).setCustomMime("application/javascript");
		try {
			return new Response(200, createStream(captions.get())).setCustomMime("application/javascript");
		} catch (Exception e) {
			JVM.errorln(e);
			return new Response(503);
		}
	}

	private static final String ID_SPLIT_PL = ".com/";
	private static final String ID_SPLIT_PATTERN = Pattern.quote(ID_SPLIT_PL);

	public static String id() {
		if (!Redwood.ENABLE_CAPTIONS)
			return null;
		Redwood.player.waitFor();
		final String s = Redwood.player_url.get().replace("base.js", "captions.js");
		try {
			return s.split(ID_SPLIT_PATTERN)[1]; // "/" + s.substring(s.indexOf(ID_SPLIT_PL) + ID_SPLIT_PL.length());
		} catch (Exception e) {
			Redwood.log.error("Failed to get captions URL! [player_url: " + Redwood.player_url.get() + "]", e);
			return null;
		}
	}

}
